package huoye.shops.base;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

public class MinePojoJsonResponseHandler<P extends MyPojo> extends MineJsonResponseHandler {
    private Class<P> genericClass;
    private P parsedPojo;
    private List<P> parsedPojos;

    public MinePojoJsonResponseHandler(Class<P> clazz) {
        super(false);
        this.genericClass = clazz;
    }

    public MinePojoJsonResponseHandler(Class<P> clazz, boolean isRecord) {
        super(isRecord);
        this.genericClass = clazz;
    }

    public P getParsedPojo() {
        return this.parsedPojo;
    }

    protected void parseRecord(JsonObject recordNode) {
        this.parsedPojo = this.jsonToPojo(recordNode);
    }

    protected P jsonToPojo(JsonObject recordNode) {
        if(this.genericClass != null) {
            P p = (P) this.jsonToBean(recordNode, this.genericClass);
            this.parsePojoExtraProperties(recordNode, p);
            if(recordNode.has("data") && recordNode.get("data").isJsonPrimitive()) {
                p.setId(recordNode.get("data").getAsString());
            }

            return p;
        } else {
            return null;
        }
    }

    protected void parsePojoExtraProperties(JsonObject recordNode, P pojo) {
    }

    public List<P> getParsedPojos() {
        return this.parsedPojos;
    }

    protected final void parseRecordset(JsonArray recordsetNodes) {
        List<P> pojos = new ArrayList();

        for(int i = 0; i < recordsetNodes.size(); ++i) {
            JsonElement element = recordsetNodes.get(i);
            if(element.isJsonObject()) {
                JsonObject recordNode = recordsetNodes.get(i).getAsJsonObject();
                pojos.add(this.jsonToPojo(recordNode));
            } else {
                pojos.add((P) null);
            }
        }

        this.parsedPojos = pojos;
    }
}